package org.bjf.runner;

import lombok.extern.slf4j.Slf4j;
import org.bjf.modules.sys.bean.AuthModuleBean;
import org.bjf.modules.sys.annotation.AuthModule;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 后置处理器，所有bean初始化后都会回调此方法
 *
 * @author bjf
 */
@Component
@Slf4j
public class LiveBeanPostProcessor implements BeanPostProcessor {

    public static Map<String, AuthModuleBean> AUTHMODULE_MAP = new LinkedHashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        Class<?> clz = bean.getClass();
        AuthModule authModule = clz.getAnnotation(AuthModule.class);

        //扫描类上所有的Module注解
        if (authModule != null) {
            if (clz.getAnnotation(RestController.class) != null || clz.getAnnotation(Controller.class) != null) {
                String resSn = authModule.code();
                if (AUTHMODULE_MAP.containsKey(resSn)) {
                    return bean;
                }

                AuthModuleBean moduleBean = new AuthModuleBean()
                        .setCode(authModule.code())
                        .setDesc(authModule.desc());

                AUTHMODULE_MAP.put(resSn, moduleBean);
            }
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
